package com.org.msmvc.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import com.org.msmvc.sys.entity.SysDictDTO;
import com.org.msmvc.sys.service.SysDictAPI;
import com.org.msmvc.sys.service.SysDictService;
import com.org.msmvc.sys.service.impl.SysDictServiceImpl;
/**
 * 数据字典
 * @author zsh
 *
 */
@Controller
@RequestMapping("sysDict" )
public class SysDictController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(SysDictController.class);
	@Autowired
	private SysDictService sysDictService;

	@RequestMapping({ "/query/{operate}" })
	public ModelAndView execute(@PathVariable("operate") String operate)

	{
		ModelAndView model = new ModelAndView();
		if ("toSysDictList".equals(operate)) {
			model.setViewName("/sysdict/sysDict/querySysDict");
		} else if ("toAdd".equals(operate)) {
			model.setViewName("/sysdict/sysDict/addSysDict");
		} else if ("toUpdate".equals(operate)) {
			String id = getParameterString("id");
			model = queryOneDTO(id);
			model.setViewName("/sysdict/sysDict/updateSysDict");
		} else if ("toView".equals(operate)) {
			String id = getParameterString("id");
			model = queryOneDTO(id);
			model.setViewName("/sysdict/sysDict/viewSysDict");
		}else if ("toSysDictDetailList".equals(operate)) {
			model.setViewName("/sysdict/sysDictDetail/querySysDictDetail");
		}
		return model;
	}

	@RequestMapping(value ="/queryListSysDict" )
	@ResponseBody
	public Map<String, Object> queryListSysDict(SysDictDTO dto,
			HttpServletRequest request, HttpServletResponse response)
			throws java.lang.Exception {
		/**
		 * 想要在页面展现数据,必须返回ModelAndView类型,返回String是不能获取数据的
		 */
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dto", dto);
		// long totalCount = rolesService.pageCounts(params); // 获取记录总数
		// 每页显示的记录数
		String pageSize = request.getParameter("pagesize");
		// 当前页
		String page = request.getParameter("page");
		// ($page-1)*$pagesize
		int startIndex = (Integer.valueOf(page) - 1)
				* Integer.valueOf(pageSize);
		params.put("startIndex", startIndex);
		params.put("pageSize", Integer.valueOf(pageSize));
		List<SysDictDTO> list = sysDictService.searchSysDictByPaging(params);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list);
		map.put("Total", list.size());
		return map;
	}

	@RequestMapping(value =  "/insertSysDict" )
	@ResponseBody
	public Map insertSysDict(HttpServletRequest request, SysDictDTO dto) throws java.lang.Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag = false;
		String message = "";
		int i = 0;
		i = sysDictService.insertSysDict(dto);
		if (i > 0) {
			flag = true;
			message = "数据新增成功";
		} else {
			message = "数据新增失败";
		}
		map.put("message", message);
		map.put("flag", flag);
		return map;
	}

	@RequestMapping(value = "/updateSysDict")
	@ResponseBody
	public Map updateSysDict(HttpServletRequest request, SysDictDTO dto) throws java.lang.Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag=false;
		String message="";
		int i = 0;
		i = sysDictService.updateSysDict(dto);
		if(i>0){
			flag=true;
			message="数据更新成功";
		}else{
			message="数据更新失败";
		}
		map.put("message",message);
		map.put("flag",flag);
		return map;
	}

	@RequestMapping(value = "/deleteSysDict")
	@ResponseBody
	public Map deleteSysDict(HttpServletRequest request,@RequestParam("id") String id) throws java.lang.Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag=false;
		String message="";
		int i = 0;
		i = sysDictService.deleteSysDictByPrimaryKey(null, id);
		if(i>0){
			flag=true;
			message="数据删除成功";
		}else{
			message="数据删除失败";
		}
		map.put("message",message);
		map.put("flag",flag);
		return map;
	}

	private ModelAndView queryOneDTO(String id) {
		ModelAndView model = new ModelAndView();
		SysDictDTO dto;
		try {
			dto = sysDictService.querySysDictByPrimaryKey(id);
			model.addObject("dto", dto);
		} catch (java.lang.Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return model;
	}

	@RequestMapping({ "/queryTreeJSON" })
	@ResponseBody
	/*public List<Map<String, String>> queryTreeJSON(HttpServletRequest request,
			@ModelAttribute DataMsg dataMsg) throws Exception {
		String codeType = request.getParameter("codeType");
		String used = request.getParameter("used");

		WebApplicationContext webApplicationContext = ContextLoader
				.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext
				.getServletContext();
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		SysDictAPI sysDictAPI = (SysDictAPI) context.getBean("sysDictAPI");

		List<Map> list = new ArrayList();
		try {
			if ((used != null) && (used.length() > 0)) {
				List<Map> allList = sysDictAPI.getDictByKey(codeType);
				if ((allList != null) && (allList.size() > 0)) {
					for (int j = 0; j < allList.size(); j++) {
						if (("," + used + ",").indexOf(","
								+ ((Map) allList.get(j)).get("DICVALUE") + ",") != -1) {
							list.add(allList.get(j));
						}
					}
				}
			} else {
				list = sysDictAPI.getDictByKey(codeType);
			}
		} catch (Exception e) {
			dataMsg.setStatus("failed");
			logger.error("执行方法queryTreeJSON异常：", e);
		}
		return treeData(list);
	}*/

	private List<Map<String, String>> treeData(List<Map> data) {
		if ((data != null) && (data.size() > 0)) {
			List<Map<String, String>> maps = new ArrayList();
			for (Map dto : data) {
				Map<String, String> map = new HashMap();
				map.put("ID", dto.get("DICVALUE").toString());
				map.put("NAME", dto.get("DICNAME").toString());

				map.put("PID", "-999999");

				maps.add(map);
			}
			return maps;
		}
		return null;
	}
}
